๐Ÿ“ฆ dgeee13 / DSA

๐Ÿ“„ WordBreak.cpp ยท 65 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65/*
Pattern: 
Summary: Backtracking and checking all possible words of max len 
Time: O(2^n)
*/

int n;
bool solve(int idx, string s, int len, unordered_set<string>& dict) {
    if (idx >= n)
        return true;

    for (int i = 1; i <= len && idx + i <= n; i++) {
        string temp = s.substr(idx, i);
        if (dict.find(temp) != dict.end() && solve(idx + i, s, len, dict)) {
            return true;
        }
    }
    return false;
}

bool wordBreak(string s, vector<string>& wordDict) {
    n = s.length();
    unordered_set<string> dict(wordDict.begin(), wordDict.end());

    int max_len = 0;
    for (auto &word : wordDict) {
        max_len = max((int)word.length(), max_len);
    }

    return solve(0, s, max_len, dict);
}


/*
Pattern: Segmentation DP
Summary: Backtracking with Memoization
Time: O(n^2)  
*/

int n;
int dp[301];
bool solve(int idx, string s, int len, unordered_set<string>& dict) {
    if (idx >= n)
        return true;
    if(dp[idx] != -1) return dp[idx];
    for (int i = 1; i <= len && idx + i <= n; i++) {
        string temp = s.substr(idx, i);
        if (dict.find(temp) != dict.end() && solve(idx + i, s, len, dict)) {
            return dp[idx] = true;
        }
    }
    return dp[idx] = false;
}
bool wordBreak(string s, vector<string>& wordDict) {
    memset(dp,-1, sizeof(dp));
    n = s.length();
    unordered_set<string> dict(wordDict.begin(), wordDict.end());

    int max_len = 0;
    for (auto word : wordDict) {
        max_len = max((int)word.length(), max_len);
    }

    return solve(0, s, max_len, dict);
}